import es6 from '../../lib/es6-promise.js'
const app = getApp()
Page({
  data: {
    currentSwiperIndex: 0,
    banners:[],
    dateList: [],
    currentDateIndex: 0,
    dayName: {
      0: 'Sunday',
      1: 'Monday',
      2: 'Tuesday',
      3: 'Wednesday',
      4: 'Thursday',
      5: 'Friday',
      6: 'Saturday',
    },
    //当前日期中文字符串
    currentDateStr: '',
    /**
     * [courseList] 课程类型有以下几种：
     * 1.免费体验；2.满员排队；3.收费；4.已预约；5.满员正在排队
     * 课程名额tag状态有:
     * 1.满员；2.排队中；3.名额紧张
     *
     * 课程类型可以抽象为：免费，收费，排队
     * 课程状态可以抽象为：已预约，未预约（无名额则为排队中，立即排队），名额
     * @type {Array}
     */
    courseList: [],
    //倒计时相关
    countData: null,
    countDown: {
      hours: 0,
      mins: 0,
      secs: 0
    },
    countTimer: {},
  },
  //组件方法
  /**
   * [generateDateList]生成未来30天日期数组
   * @method generateDateList
   * @return {[Array]}        dateList [description]
   * [dateList]包含生成未来30天日期的数组，其中每个item的shape为
   * {
   *   year: 2017,
   *   month: 01,
   *   date: 02,
   *   day: 03,
   *   day_str: 'Monday',
   *   day_min_str: 'Mon'
   * }
   */
  generateDateList(dateCount){
    const dayNameMap = this.data.dayName
    let currentDate = new Date(),
        dateList = []
    for(let i = 0;i < dateCount;i++){
      let dateItem = {
        year: currentDate.getFullYear(),
        month: currentDate.getMonth() + 1,
        date: currentDate.getDate(),
        day: currentDate.getDay(),
      }
      dateItem.day_str = dayNameMap[dateItem.day]
      //day缩写
      dateItem.day_min_str = dateItem.day_str.slice(0,3)
      dateList.push(dateItem)
      currentDate.setDate(currentDate.getDate() + 1)
    }
    return dateList
  },
  /**
   * [generateCurDate] 生成当前日期中文字符串
   * @method generateCurDate
   * @return [String] 当前日期中文字符串
   */
  generateCurDate(){
    const now = new Date(),
          year = now.getFullYear(),
          month = now.getMonth() + 1,
          date = now.getDate(),
          day = now.getDay(),
          dayName = {
            0: '天',
            1: '一',
            2: '二',
            3: '三',
            4: '四',
            5: '五',
            6: '六',
          }
    let curDayName = `星期${dayName[day]}`
    return `${year}年${month}月${date}日 ${curDayName}`
    // currentDateStr
  },
  /**
   * [formatTime] 根据deadline日期的时间戳，计算出倒计时所需要的时间格式，如 5:30:22
   * @method formatTime
   * @param  {Number}   countDownTimeStamp [deadline时间戳]
   * @return {Object}                      [格式化的时间, shape为{ hours:5, mins:30, secs: 22 }]
   */
  formatTime(deadline){
    let remaining = deadline - new Date().getTime(),
          millsec = 36e5,
          a_hours = remaining/millsec,
          hours = Math.floor(a_hours) + '',
          a_mins = (a_hours - hours) * 60,
          mins = Math.floor(a_mins) + '',
          secs = Math.floor((a_mins - mins) * 60) + ''
    if(mins < 10){
      mins = '0' + mins
    }
    if(secs < 10){
      secs = '0' + secs
    }
    return {
      hours,
      mins,
      secs,
      remaining
    }
  },
  setTime(){
    const { hours, mins, secs, remaining } = this.formatTime(this.data.countData.deadline)
    this.setData({
      countDown: {
        hours,
        mins,
        secs
      }
    })
    console.log(this.data.countDown);
    return remaining
  },
  /**
   * [countDownInterval] 定时修改组件中已格式化的时间(this.data.countDown)
   */
  countDownInterval(){
    const self = this
    const init_remaing = this.setTime()
    if(init_remaing > 1000){
      const timer = setInterval(() => {
        let this_remaing = this.setTime()
        if(this_remaing <= 1000){
          clearInterval(timer)
        }
        console.log(this_remaing);
      }, 1000)
      //缓存timer id
      this.setData({
        countTimer: timer
      })
    }
  },
  /**
   * [getCourseList description]
   * @method getCourseList
   * @param  {[type]}      startDate [description]
   * @return {[type]}           [description]
   */
  getCourseList(startDate){
    return new es6.Promise((resolve, reject) => {
      app.$http.POST('/api/subject/ajax', {startDate})
      .then(data => {
        resolve(data.data.records)
      })
      .catch(e => {
        reject(e)
      })
    })
  },
  formatTodayTime(){
    const now = new Date(),
          year = now.getFullYear(),
          month = now.getMonth() + 1,
          date = now.getDate()
    return `${year}-${month}-${date}`
  },
  //事件处理函数
  bindSelectDate(event) {
    const target = event.currentTarget.dataset
    const index = parseInt(target.index, 10)
    this.setData({
      currentDateIndex: index
    })
    let currentDate = this.data.dateList[index]
    this.getCourseList(`${currentDate.year}-${currentDate.month}-${currentDate.date}`)
    .then(courseList => {
      this.setData({
        courseList
      })
    })
  },
  bindSwiperChange(evt){
    this.setData({
      currentSwiperIndex: evt.detail.current
    })
  },
  bindGoToOrder(evt){
    const order_id = evt.currentTarget.dataset.order
    wx.navigateTo({
      url: `../order/order?order_id=${order_id}`,
    })
  },
  bindGoToDetail(evt){
    const dataset = evt.currentTarget.dataset
    const isOrder = dataset.isorder
    if(isOrder){
      wx.navigateTo({
        url: `../order/order?order_id=${dataset.order_id}`,
      })
    } else {
      wx.navigateTo({
        url: `../course/course?subject_id=${dataset.subject_id}`,
      })
    }
  },
  //生命周期函数
  onLoad() {
    console.log('onLoad')
    /**
     * UI逻辑部分
     */
    this.setData({
      //未来30天日期列表
      dateList: this.generateDateList(30),
      //初始化当前日期中文字符串
      currentDateStr: this.generateCurDate()
    })
    /**
     * 数据逻辑部分:
     * 1.获取课程列表流程：
     *    1.并行操作之一:无登录态获取默认地址的课程列表，作展示用(不可交互)
     *    2.并行操作之二:获取用户地址 => 用户登录 => 调用注册接口 => 获取当前用户于当前地址的课程列表
     */
    let locationData = {},
        userData = {}
     app.getLocation()
     .then(location => {
       locationData = location
       return app.getUser()
     })
     .then(user => {
       userData = user
       return app.registerUser(userData, locationData)
     })
     .then(final => {
       // TODO:测试代码
      //  const now = this.formatTodayTime()
       return this.getCourseList('2017-01-18')
     })
     .then(courseList => {
       this.setData({
         courseList
       })
     })
     /**
      * 2.获取banners
      */
     app.$http.GET('/api/banner/index')
     .then(data => {
       this.setData({
         banners: data.data
       })
     })
     /**
      * 3.获取倒计时
      */
     app.$http.GET('/api/subject/countdown')
     .then(res => {
       const data = res.data
       this.setData({
         countData: {
           deadline: data.startTime * 1000,
           order_id: data.orderId,
           course_name: data.subjectName
         }
       })
       //启用倒计时逻辑
       this.countDownInterval()
     })
  },
  onUnload(){
    const timer = this.data.countTimer
    clearInterval(this.data.countTimer)
  }
})
